package com.newcamping.wechat.core;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @auth zhaoly
 * @date 2024-01-25 10:01
 */
@Component
public class WxCore {

    @Value("${wechat.wxAppid}")
    private String wxAppid;

    @Value("${wechat.wxSecret}")
    private String wxSecret;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 用预登录code向微信换取openId
     * @param code
     * @return
     */
    public String getOpenId(String code){
        try{
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
            url = String.format(url, wxAppid, wxSecret, code);
            System.out.println("向微信服务器请求OpenId：" + url);

            String str = restTemplate.getForObject(url, String.class);

            System.out.println("微信服务器返回内容：" + str);

            JSONObject obj = (JSONObject) JSON.parse(str);
            return obj.getString("openid");
        }catch(Exception e){

            System.out.println("用code向微信服务器换取openid失败");
            e.printStackTrace();
            return "";
        }
    }
}